from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from datetime import datetime

import util
from datamodel import Student

class EditHandler(webapp.RequestHandler):
  def get(self):
    user = util.ensure_login(self)
    #self.response.headers['Content-Type'] = 'text/html'
    entity_id = int(self.request.get('id') or 0)
    if entity_id and entity_id > 0:
      student = Student.get_by_id(entity_id)
    else:
      student = Student()
    
    if student.grad_date:
      grad_year = student.grad_date.year
    else:
      grad_year = None
    template_values = { 'entity_id': entity_id,
                        'name': student.name or '',
                        'grad_year': grad_year or '' }
    util.render_template(self, 'edit.tpl', template_values)

class SaveHandler(webapp.RequestHandler):
  def post(self):
    name = self.request.get('name')
    year = int(self.request.get('grad_year') or 2011)
    month = int(self.request.get('grad_month') or 1)
    day = int(self.request.get('grad_day') or 1)

    entity_id = int(self.request.get('id') or 0)
    if entity_id and entity_id > 0:
      student = Student.get_by_id(entity_id)
    else:
      student = Student()

    student.name = name
    student.grad_date = datetime(year, month, day).date()
    student.put()
    self.redirect('/search')

application = webapp.WSGIApplication(
                                     [('/edit', EditHandler),
                                      ('/save', SaveHandler),],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

